<template>
  <div class="app">
    <div class="content">
      <el-form
        :label-position="labelPosition"
        ref="ruleForm"
        label-width="80px"
        :model="fatherObj"
        :rules="rules"
      >
        <div class="title">基础信息</div>
        <el-form-item label="商品名称" prop="name">
          <el-input
            v-model="fatherObj.name"
            class="input"
            placeholder="请输入商品名称"
          ></el-input>
        </el-form-item>
        <el-form-item label="商品编号">
          <el-input
            v-model="fatherObj.bn"
            class="input"
            placeholder="请输入商品编号"
            disabled
          ></el-input>
          <!-- <span class="typeface">! 如需不填,编号自动生成</span> -->
        </el-form-item>
        <el-form-item label="商品单位" prop="unit">
          <!-- <el-input
            v-model="fatherObj.unit"
            class="input"
            placeholder="请输入商品单位;例:桶、瓶"
          ></el-input> -->
          <el-select
            @change="selectUnit"
            v-model="fatherObj.unit"
            placeholder="请选择"
            class="input"
          >
            <el-option
              v-for="item in this.unitList"
              :key="item.unit"
              :label="item.unit"
              :value="item.unit"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="商品规格" prop="specifications">
          <el-input
            maxlength="15"
            show-word-limit
            v-model="fatherObj.specifications"
            class="input"
            placeholder="请输入商品规格"
          ></el-input>
        </el-form-item>

        <el-form-item label="商品品牌" prop="brand_id">
          <el-select
            v-model="fatherObj.brand_id"
            placeholder="品牌"
            class="input"
          >
            <el-option
              v-for="(item, index) in pinpaiList"
              :key="index"
              :label="item.name"
              :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="商品类型" prop="goods_type_name">
          <el-select
            v-model="fatherObj.goods_type_name"
            placeholder="类型"
            class="input"
            @change="goodsType"
          >
            <el-option label="通用" value="通用"></el-option>
            <el-option label="桶装水" value="桶装水"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="商品分类" prop="goods_cat_id">
          <!--            <el-select v-model="fatherObj.goods_cat_id" placeholder="分类" class="input">-->
          <!--              <el-option  v-for="(item,index) in fenleiList" :key="index" :label="item.name" :value="item.id"></el-option>-->
          <!--            </el-select>-->
          <el-cascader
            class="input"
            v-model="selectfenleiList"
            :props="fenleiListProps"
            :options="fenleiList"
            :show-all-levels="false"
            @change="handleChange"
          ></el-cascader>
        </el-form-item>
        <el-form-item label="商品照片" prop="images">
          <el-form-item label="">
            <div class="unlodBox">
              <el-upload
                class="upload-demo"
                action
                :http-request="uploadFile"
                ref="upload"
                :limit="fileLimit"
                :on-remove="handleRemove"
                :file-list="fileList"
                :on-exceed="handleExceed"
                :before-upload="beforeUpload"
                :show-file-list="false"
                :headers="headers"
                :on-change="fileChange"
              >
                <el-button size="small" type="primary">点击上传</el-button>
                <div slot="tip" class="el-upload__tip">
                  只能上传jpg/png文件，且不超过5M
                </div>
              </el-upload>
              <el-image
                v-if="fatherObj.imagesquan"
                style="width: 100px; height: 100px"
                :src="fatherObj.imagesquan"
                fit="cover"
              ></el-image>
            </div>
          </el-form-item>
        </el-form-item>
        <div class="title">销售信息</div>
        <el-form-item label="销售价" prop="price">
          <el-input v-model="fatherObj.price" class="input"></el-input>
        </el-form-item>
        <el-form-item label="成本价" prop="costprice">
          <el-input v-model="fatherObj.costprice" class="input"></el-input>
        </el-form-item>
        <el-form-item label="市场价" prop="mktprice">
          <el-input v-model="fatherObj.mktprice" class="input"></el-input>
        </el-form-item>
        <el-form-item label="起购数量">
          <el-input-number
            v-model="fatherObj.sell_num"
            @change="handleChangeSell"
            :min="1"
            :max="1000"
            size="medium"
          ></el-input-number>
        </el-form-item>
        <el-form-item label="重量" prop="weight">
          <el-input
            v-model="fatherObj.weight"
            class="input"
            placeholder="请输入重量;单位/千克"
          ></el-input>
          &nbsp;/千克
        </el-form-item>
        <el-form-item label="库存" prop="stock">
          <el-input v-model="fatherObj.stock" class="input"></el-input>
        </el-form-item>
        <el-form-item label="上下架">
          <el-switch
            v-model="fatherObj.marketable"
            active-color="#13ce66"
            inactive-color="#ff4949"
            :active-value="1"
            :inactive-value="2"
            @change="switchChange(fatherObj.marketable)"
          >
          </el-switch>
        </el-form-item>
        <el-form-item label="热门">
          <el-switch
            v-model="fatherObj.is_hot"
            active-color="#13ce66"
            inactive-color="#ff4949"
            :active-value="1"
            :inactive-value="2"
            @change="switchChange2(fatherObj.is_hot)"
          >
          </el-switch>
        </el-form-item>
      </el-form>
    </div>
    <div class="footer">
      <el-button @click="save('ruleForm')">保存</el-button>
      <el-button @click="back">返回</el-button>
    </div>
  </div>
</template>

<script>
import {
  allBrand,
  goodSort,
  addGood,
  uploadFilec,
  brandList,
  getUnitList,
} from "../../utils/api";
import { compressImage } from "../../assets/js/compressImage";
export default {
  name: "addGoods",
  data() {
    return {
      unitList: [],
      token: sessionStorage.getItem("token"),
      labelPosition: "right",
      pinpaiList: [],
      fenleiList: [],
      image: "",
      fatherObj: {
        name: "",
        goods_cat_id: "",
        brand_id: "",
        goods_type_id: "",
        price: "",
        costprice: "",
        mktprice: "",
        weight: "0.00",
        stock: "0",
        unit: "",
        images: "",
        marketable: "",
        is_hot: "",
        bn: "",
        specifications: "",
        sell_num: "",
      },
      fenleiListProps: {
        label: "name",
        value: "id",
        children: "child",
      },
      selectfenleiList: [],
      fileLimit: 1,
      fileType: ["png", "jpg", "jpeg"],
      fileList: [],
      headers: { "Content-Type": "multipart/form-data" },
      srcList2: {},
      rules: {
        name: [
          { required: true, message: "请输入商品名称", trigger: "change" },
        ],
        unit: [
          { required: true, message: "请输入商品单位", trigger: "change" },
        ],
        specifications: [
          { required: true, message: "请输入商品规格", trigger: "change" },
        ],
        brand_id: [
          { required: true, message: "请选择商品品牌", trigger: "change" },
        ],
        goods_type_name: [
          { required: true, message: "请选择商品类型", trigger: "change" },
        ],
        goods_cat_id: [
          { required: true, message: "请选择商品分类", trigger: "change" },
        ],
        images: [
          { required: true, message: "请上传商品照片", trigger: "change" },
        ],
        price: [
          { required: true, message: "请输入商品销售价", trigger: "change" },
          {
            validator: (rule, value, callback) => {
              var reg = /^(?!0+(?:\.0+)?$)(?:0|[1-9]\d*)(?:\.\d{1,2})?$/;
              if (!reg.test(value)) {
                callback(new Error("请输入不小于0且不超过两位小数的数字"));
              }
              if (value > 99999999.99) {
                callback(new Error("不能大于99999999.99"));
              } else {
                callback();
              }
            },
            trigger: "blur",
          },
        ],
        costprice: [
          { required: true, message: "请输入成本价格", trigger: "change" },
          {
            validator: (rule, value, callback) => {
              var reg = /^(?!0+(?:\.0+)?$)(?:0|[1-9]\d*)(?:\.\d{1,2})?$/;
              if (!reg.test(value)) {
                callback(new Error("请输入不小于0且不超过两位小数的数字"));
              }
              if (value > 99999999.99) {
                callback(new Error("不能大于99999999.99"));
              } else {
                callback();
              }
            },
            trigger: "blur",
          },
        ],
        mktprice: [
          { required: true, message: "请输入市场价格", trigger: "change" },
          {
            validator: (rule, value, callback) => {
              var reg = /^(?!0+(?:\.0+)?$)(?:0|[1-9]\d*)(?:\.\d{1,2})?$/;
              if (!reg.test(value)) {
                callback(new Error("请输入不小于0且不超过两位小数的数字"));
              }
              if (value > 99999999.99) {
                callback(new Error("不能大于99999999.99"));
              } else {
                callback();
              }
            },
            trigger: "blur",
          },
        ],
        weight: [
          { required: true, message: "请输入商品重量", trigger: "change" },
          {
            validator: (rule, value, callback) => {
              var reg = /^(?!0+(?:\.0+)?$)(?:0|[1-9]\d*)(?:\.\d{1,2})?$/;
              if (!reg.test(value)) {
                callback(new Error("请输入不小于0且不超过两位小数的数字"));
              }
              if (value > 99999999.99) {
                callback(new Error("不能大于99999999.99"));
              } else {
                callback();
              }
            },
            trigger: "blur",
          },
        ],
        stock: [
          { required: true, message: "请输入商品库存", trigger: "change" },
          {
            validator: (rule, value, callback) => {
              var reg = /^(0|[1-9]\d*)$/;
              if (!reg.test(value)) {
                callback(new Error("请输入不小于0的整数"));
              }
              if (value > 999999999) {
                callback(new Error("不能大于999999999"));
              } else {
                callback();
              }
            },
            trigger: "blur",
          },
        ],
      },
      saveFlag: true,
    };
  },
  watch: {
    fatherObj: {
      handler(val, oldVal) {
        if (val.goods_type_name == "桶装水") {
          this.fatherObj.goods_type_id = 1;
        }
        if (val.goods_type_name == "通用") {
          this.fatherObj.goods_type_id = 2;
        }
      },
      deep: true,
    },
  },
  methods: {
    fileChange(file, fileList) {
      this.fileList = fileList;
    },
    // 压缩文件
    compressFile() {
      let config = {
        quality: 0.5, //默认0.5  0-1
        // width:100,
        // height:100
      };
      this.fileList.forEach(async (item) => {
        // console.log("this.fileList1", this.fileList1);
        console.log("原图size1===>", item.size);
        let result = await compressImage({
          file: item.raw,
          config,
          fileName: item.name,
        });
        console.log("压缩后图片size1===>", result.finalFile.size);
        // this.imageList.push(result);
        this.srcList2 = result.finalFile;
        // console.log("aaa", result.finalFile);
        // console.log("bbb", this.srcList2);
        // console.log("this.srcList", this.srcList);
      });
      // console.log("压缩后图片1===>", this.imageList);
    },
    uploadFile(item) {
      this.$message("文件上传中........");
      //上传文件的需要formdata类型;所以要转
      this.compressFile();
      let timer = setTimeout(() => {
        uploadFilec(this.srcList2).then((res) => {
          if (res.data.status != false || res.data.id != null) {
            res.data.data.saveurl; //半截
            res.data.data.weburl; //全拼
            this.fatherObj.imagesquan = res.data.data.weburl;
            this.fatherObj.images = res.data.data.saveurl;
            // this.fileList.push(this.srcList2); //成功过后手动将文件添加到展示列表里
            // let i = this.fileList.indexOf(this.srcList2);
            this.handleSuccess();
          }
        });
        clearTimeout(timer);
      }, 1000);
      // uploadFilec(item.file).then((res) => {
      //   if (res.data.status != false || res.data.id != null) {
      //     res.data.data.saveurl; //半截
      //     res.data.data.weburl; //全拼
      //     this.fatherObj.imagesquan = res.data.data.weburl;
      //     this.fatherObj.images = res.data.data.saveurl;
      //     this.fileList.push(item.file); //成功过后手动将文件添加到展示列表里
      //     let i = this.fileList.indexOf(item.file);
      //     this.handleSuccess();
      //   }
      // });
    },
    selectUnit(e) {
      console.log(e);
    },
    //上传成功后的回调
    handleSuccess() {
      this.$message({
        message: "上传成功",
        type: "success",
      });
      this.handleClose();
    },
    handleRemove() {},
    beforeUpload(file) {
      if (file.type != "" || file.type != null || file.type != undefined) {
        //截取文件的后缀，判断文件类型
        const FileExt = file.name.replace(/.+\./, "").toLowerCase();
        //计算文件的大小
        const isLt5M = file.size / 1024 / 1024 < 1; //这里做文件大小限制
        //如果大于50M
        if (!isLt5M) {
          this.$message.error("上传文件大小不能超过 1MB!");
          return false;
        }
        //如果文件类型不在允许上传的范围内
        if (this.fileType.includes(FileExt)) {
          return true;
        } else {
          this.$message.error("上传文件格式不正确!");
          return false;
        }
      }
    },
    handleClose(i) {
      this.fileList.splice(i, 1); //删除上传的文件
    },
    //超出文件个数的回调
    handleExceed() {
      this.$message({
        type: "warning",
        message: "超出最大上传文件数量的限制！",
      });
      return;
    },
    handleChange(e) {
      this.fatherObj.goods_cat_id = this.selectfenleiList[1];
    },
    handleChangeSell(e) {},
    unloadImg() {},
    goodsType(e) {},
    switchChange(e) {
      this.fatherObj.marketable = e;
    },
    switchChange2(e) {
      this.fatherObj.is_hot = e;
    },
    back() {
      this.$emit("back");
    },
    save(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          if (!this.saveFlag) {
            return;
          }
          this.saveFlag = false;
          addGood(
            this.token,
            this.fatherObj.name,
            this.fatherObj.goods_cat_id,
            this.fatherObj.brand_id,
            this.fatherObj.goods_type_id,
            this.fatherObj.price,
            this.fatherObj.costprice,
            this.fatherObj.mktprice,
            this.fatherObj.weight,
            this.fatherObj.stock,
            this.fatherObj.unit,
            this.fatherObj.images,
            this.fatherObj.marketable,
            this.fatherObj.is_hot,
            this.fatherObj.bn,
            this.fatherObj.specifications,
            this.fatherObj.sell_num
          ).then((res) => {
            if (res.data.status) {
              this.$message({
                message: "操作成功",
                type: "success",
                onClose: (res) => {
                  this.$emit("back");
                },
              });
            } else {
              if (res.data.msg == "token失效,请重新进行登录") {
                this.$router.push("/login");
              }
            }
          });
        } else {
          console.log("error submit!!");
          return false;
        }
      });
      // if(!this.fatherObj.unit){
      //   this.$message.error('请输入商品单位')
      //   return
      // }
      // if(!this.fatherObj.specifications){
      //   this.$message.error('请输入商品规格')
      //   return
      // }
      // if(!this.fatherObj.brand_id){
      //   this.$message.error('请选择商品品牌')
      //   return
      // }
      // if(!this.fatherObj.goods_type_id){
      //   this.$message.error('请选择商品类型')
      //   return
      // }
      // if(!this.fatherObj.goods_type_id==1&&!this.fatherObj.brand){
      //   this.$message.error('请输入水票名称')
      //   return
      // }
      // if(!this.fatherObj.goods_cat_id){
      //   this.$message.error('请选择商品分类')
      //   return
      // }
    },
    initialize() {
      // allBrand(sessionStorage.getItem('token'), 1).then(res => {
      //   console.log(res,'=-=-=-=-=-=-==');
      //   if (res.data.status) {
      //     this.pinpaiList = res.data.data

      //   } else {
      //     this.$message.error(res.data.msg)
      //   }
      // }).catch(err => {
      //   this.$message.error(err.message)
      // })
      brandList(this.token, 1, 100000000000000000000, "", 1)
        .then((res) => {
          if (res.data.status) {
            this.pinpaiList = res.data.data.data;
          } else {
            this.$message.error(res.data.msg);
          }
        })
        .catch((err) => {
          this.$message.error(err.message);
        });
      goodSort(sessionStorage.getItem("token"), 1, "")
        .then((res) => {
          if (res.data.status) {
            console.log(res.data.data);
            this.fenleiList = res.data.data;
            this.fenleiList = this.fenleiList.filter(function (item) {
              return item.id !== 80;
            });
          } else {
            this.$message.error(res.data.msg);
          }
        })
        .catch((err) => {
          this.$message.error(err.message);
        });
      getUnitList(this.token, 1).then((res) => {
        if (res.data.status) {
          this.unitList = res.data.data.data;
          console.log();
          // if (this.fatherObj.id) {
          //   this.fatherObj.unit = this.fatherObj.unit;
          //   console.log(this.fatherObj.unit);
          // }
        }
      });
    },
  },
  created() {
    this.initialize();
  },
};
</script>

<style scoped>
.app {
  padding: 10px;
}

.content {
  box-shadow: 0 2px 4px 0 rgba(0, 0, 0, 0.12), 0 0 6px 0 rgba(0, 0, 0, 0.04);
  max-height: 80vh;
  overflow: auto;
}

.footer {
  margin: 10px auto;
  width: 50%;
  display: flex;
  justify-content: center;
}
.typeface {
  color: #800080;
  margin-left: 10px;
}
.el-form-item .input {
  width: 280px;
}

.title {
  display: block;
  margin-bottom: 20px;
  text-indent: 1em;
}

.upload-demo .el-upload--text {
  border: none;
  width: auto;
  height: auto;
}

.upload-demo {
  line-height: normal;
  margin-bottom: 20px;
}
</style>
